package com.demo.springsecuritystudy.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

//@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Value("${application.customize.username:admin}")
    private String customizeUsername;

    @Value("${application.customize.password:123}")
    private String customizePassword;

    @Value("${application.customize.permission.list:admin,normal,ROLE_hello,/main.html}")
    private String permissionList;

//    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户名是否在数据存在,如果不存在抛出异常
        if (!customizeUsername.equals(username)) {
            throw new UsernameNotFoundException("用户名不存在: {}" + username);
        }
        // 如果查询到密码的密码进行解析,或者总结把密码传入构造方法
        String password = passwordEncoder.encode(customizePassword);
        // 使用AuthorityUtils构造权限列表
        return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList(permissionList));
    }
}
